package com.ruoyi.web.controller.customer;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.api.domain.RecRecord;
import com.ruoyi.api.service.IRecRecordService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * Customer权限识别记录Controller
 * 
 * @author ruoyi
 * @date 2025-01-15
 */
@RestController
@RequestMapping("/customer/recRecord")
public class CustomerRecRecordController extends BaseController
{
    @Autowired
    private IRecRecordService recRecordService;

    /**
     * 查询识别记录列表（仅显示当前用户创建的记录）
     */
    @PreAuthorize("@ss.hasRole('customer')")
    @GetMapping("/list")
    public TableDataInfo list(RecRecord recRecord)
    {
        startPage();
        // 只查询当前用户创建的记录
        recRecord.setCreateBy(getUsername());
        List<RecRecord> list = recRecordService.selectRecRecordList(recRecord);
        return getDataTable(list);
    }

    /**
     * 导出识别记录列表
     */
    @PreAuthorize("@ss.hasRole('customer')")
    @Log(title = "识别记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RecRecord recRecord)
    {
        // 只导出当前用户创建的记录
        recRecord.setCreateBy(getUsername());
        List<RecRecord> list = recRecordService.selectRecRecordList(recRecord);
        ExcelUtil<RecRecord> util = new ExcelUtil<RecRecord>(RecRecord.class);
        util.exportExcel(response, list, "识别记录数据");
    }

    /**
     * 获取识别记录详细信息
     */
    @PreAuthorize("@ss.hasRole('customer')")
    @GetMapping(value = "/{recordId}")
    public AjaxResult getInfo(@PathVariable("recordId") Long recordId)
    {
        RecRecord recRecord = recRecordService.selectRecRecordByRecordId(recordId);
        // 验证记录是否属于当前用户
        if (recRecord == null || !getUsername().equals(recRecord.getCreateBy())) {
            return error("无权限查看此记录");
        }
        return success(recRecord);
    }

    /**
     * 新增识别记录
     */
    @PreAuthorize("@ss.hasRole('customer')")
    @Log(title = "识别记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RecRecord recRecord)
    {
        recRecord.setCreateBy(getUsername());
        return toAjax(recRecordService.insertRecRecord(recRecord));
    }

    /**
     * 修改识别记录
     */
    @PreAuthorize("@ss.hasRole('customer')")
    @Log(title = "识别记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RecRecord recRecord)
    {
        // 验证记录是否存在且属于当前用户
        RecRecord existingRecord = recRecordService.selectRecRecordByRecordId(recRecord.getRecordId());
        if (existingRecord == null || !getUsername().equals(existingRecord.getCreateBy())) {
            return error("无权限修改此记录");
        }
        
        recRecord.setUpdateBy(getUsername());
        return toAjax(recRecordService.updateRecRecord(recRecord));
    }

    /**
     * 删除识别记录
     */
    @PreAuthorize("@ss.hasRole('customer')")
    @Log(title = "识别记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{recordIds}")
    public AjaxResult remove(@PathVariable Long[] recordIds)
    {
        // 验证所有记录是否属于当前用户
        for (Long recordId : recordIds) {
            RecRecord existingRecord = recRecordService.selectRecRecordByRecordId(recordId);
            if (existingRecord == null || !getUsername().equals(existingRecord.getCreateBy())) {
                return error("无权限删除记录ID: " + recordId);
            }
        }
        
        return toAjax(recRecordService.deleteRecRecordByRecordIds(recordIds));
    }

    /**
     * 获取识别统计信息
     */
    @PreAuthorize("@ss.hasRole('customer')")
    @GetMapping("/stats")
    public AjaxResult getStats(@RequestParam(required = false) String startDate,
                              @RequestParam(required = false) String endDate,
                              @RequestParam(required = false) Long deviceId)
    {
        RecRecord queryRecord = new RecRecord();
        queryRecord.setCreateBy(getUsername());
        if (deviceId != null) {
            queryRecord.setDeviceId(deviceId);
        }
        
        List<RecRecord> records = recRecordService.selectRecRecordList(queryRecord);
        
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalRecords", records.size());
        
        long dangerCount = records.stream().filter(r -> r.getDanger() != null && r.getDanger() == 1).count();
        stats.put("dangerRecords", dangerCount);
        
        long processedCount = records.stream().filter(r -> "已处理".equals(r.getProcessStatus())).count();
        stats.put("processedRecords", processedCount);
        
        // 计算平均置信度
        double avgConfidence = records.stream()
            .filter(r -> r.getConfidence() != null)
            .mapToDouble(r -> r.getConfidence().doubleValue())
            .average()
            .orElse(0.0);
        stats.put("avgConfidence", BigDecimal.valueOf(avgConfidence).setScale(2, BigDecimal.ROUND_HALF_UP));
        
        return success(stats);
    }

    /**
     * 获取预警记录
     */
    @PreAuthorize("@ss.hasRole('customer')")
    @GetMapping("/danger")
    public TableDataInfo getDangerRecords(RecRecord recRecord)
    {
        startPage();
        // 只查询当前用户的预警记录
        recRecord.setCreateBy(getUsername());
        recRecord.setDanger(1); // 只查询预警记录
        List<RecRecord> list = recRecordService.selectRecRecordList(recRecord);
        return getDataTable(list);
    }

    /**
     * 标记记录为已处理
     */
    @PreAuthorize("@ss.hasRole('customer')")
    @Log(title = "识别记录", businessType = BusinessType.UPDATE)
    @PutMapping("/process/{recordId}")
    public AjaxResult markProcessed(@PathVariable Long recordId)
    {
        RecRecord existingRecord = recRecordService.selectRecRecordByRecordId(recordId);
        if (existingRecord == null || !getUsername().equals(existingRecord.getCreateBy())) {
            return error("无权限处理此记录");
        }
        
        RecRecord updateRecord = new RecRecord();
        updateRecord.setRecordId(recordId);
        updateRecord.setProcessStatus("已处理");
        updateRecord.setUpdateBy(getUsername());
        
        return toAjax(recRecordService.updateRecRecord(updateRecord));
    }

    /**
     * 批量标记记录为已处理
     */
    @PreAuthorize("@ss.hasRole('customer')")
    @Log(title = "识别记录", businessType = BusinessType.UPDATE)
    @PutMapping("/process/batch")
    public AjaxResult markBatchProcessed(@RequestBody Map<String, Object> params)
    {
        @SuppressWarnings("unchecked")
        List<Long> recordIds = (List<Long>) params.get("recordIds");
        
        if (recordIds == null || recordIds.isEmpty()) {
            return error("请选择要处理的记录");
        }
        
        // 验证所有记录是否属于当前用户
        for (Long recordId : recordIds) {
            RecRecord existingRecord = recRecordService.selectRecRecordByRecordId(recordId);
            if (existingRecord == null || !getUsername().equals(existingRecord.getCreateBy())) {
                return error("无权限处理记录ID: " + recordId);
            }
        }
        
        int successCount = 0;
        for (Long recordId : recordIds) {
            RecRecord updateRecord = new RecRecord();
            updateRecord.setRecordId(recordId);
            updateRecord.setProcessStatus("已处理");
            updateRecord.setUpdateBy(getUsername());
            
            if (recRecordService.updateRecRecord(updateRecord) > 0) {
                successCount++;
            }
        }
        
        return success("成功处理 " + successCount + " 条记录");
    }

    /**
     * 重新识别
     */
    @PreAuthorize("@ss.hasRole('customer')")
    @Log(title = "识别记录", businessType = BusinessType.UPDATE)
    @PostMapping("/reRecognize/{recordId}")
    public AjaxResult reRecognize(@PathVariable Long recordId)
    {
        RecRecord existingRecord = recRecordService.selectRecRecordByRecordId(recordId);
        if (existingRecord == null || !getUsername().equals(existingRecord.getCreateBy())) {
            return error("无权限重新识别此记录");
        }
        
        // 这里可以添加重新识别的逻辑
        // 目前只是更新状态为"处理中"
        RecRecord updateRecord = new RecRecord();
        updateRecord.setRecordId(recordId);
        updateRecord.setProcessStatus("处理中");
        updateRecord.setUpdateBy(getUsername());
        
        return toAjax(recRecordService.updateRecRecord(updateRecord));
    }

    /**
     * 获取识别记录的图片
     */
    @PreAuthorize("@ss.hasRole('customer')")
    @GetMapping("/image/{recordId}")
    public AjaxResult getRecordImage(@PathVariable Long recordId, 
                                   @RequestParam(defaultValue = "input") String type)
    {
        RecRecord existingRecord = recRecordService.selectRecRecordByRecordId(recordId);
        if (existingRecord == null || !getUsername().equals(existingRecord.getCreateBy())) {
            return error("无权限查看此记录的图片");
        }
        
        Map<String, Object> result = new HashMap<>();
        if ("input".equals(type)) {
            result.put("imageUrl", existingRecord.getInputImg());
        } else if ("output".equals(type)) {
            result.put("imageUrl", existingRecord.getOutputImg());
        } else {
            return error("无效的图片类型");
        }
        
        return success(result);
    }

    /**
     * 下载识别结果
     */
    @PreAuthorize("@ss.hasRole('customer')")
    @GetMapping("/download/{recordId}")
    public void downloadRecordResult(@PathVariable Long recordId, HttpServletResponse response)
    {
        RecRecord existingRecord = recRecordService.selectRecRecordByRecordId(recordId);
        if (existingRecord == null || !getUsername().equals(existingRecord.getCreateBy())) {
            return;
        }
        
        try {
            String fileName = "recognition_result_" + recordId + ".json";
            response.setContentType("application/json");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            
            String result = existingRecord.getRecResult();
            if (StringUtils.isNotEmpty(result)) {
                response.getWriter().write(result);
            }
        } catch (Exception e) {
            logger.error("下载识别结果失败", e);
        }
    }
}